package c2c

import (
	"errors"
	"gim-server/apis/ws"
	"gim-server/errs"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type WithdrawC2cMsg struct {
	MsgID int64 `json:"msg_id"`
}

func withdrawC2cMsg(ctx *gin.Context) {
	var (
		err  error
		args = new(WithdrawC2cMsg)
	)
	if err = ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	db := sdk.DB(ctx)
	msg := new(model.TbC2cMsgRecord)
	if err = db.First(msg, "id = ?", args.MsgID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiRecordNotFound,
				Err:  err,
			})
		} else {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiDbErr,
				Err:  err,
			})
		}
		return
	}
	if msg.CreatedAt < time.Now().Unix()-120 {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiWithDrawTimeout,
		})
		return
	}
	if err = db.Delete(msg).Error; err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiDbErr,
			Err:  err,
		})
		return
	}
	time.AfterFunc(time.Second, func() {
		ws.WithdrawC2cMsg(msg.ToUID, msg.ID, !msg.Readed)
	})
	utils.SUC(ctx, true)
}
